package com.rjj.wlqq.pdf;

import com.jfinal.template.Engine;
import com.jfinal.template.Template;
import org.springframework.util.ResourceUtils;

import java.io.FileNotFoundException;
import java.util.Map;

public class TemplateToPDFJfinal extends BasePDF{
    private static String path;
    private static Engine myEngine;

    /**
     * 这里在加载配置文件的时候就加载就好了，项目中启动时候就设置这个，那么，就会一只存在，直到项目停止
     * @param myEngine 模版引擎
     */
    public static void setEngine(Engine myEngine) {
        TemplateToPDFJfinal.myEngine = myEngine;
    }

    static {
        try {
            path = ResourceUtils.getURL("classpath:templates/pdf/").getPath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
    @Override
    public String templateToString(Map<String, Object> data, String htmlTmp) {
        //这里需要改动，因为创建了，下次可以直接获取
        //Engine myEngine = Engine.create("myEngine");

        if(myEngine == null){
            //自动使用jfinal默认模版引擎
            myEngine = Engine.use();
            System.out.println("模版引擎 == 【 null 】,使用默认的！");
            //throw new RuntimeException("Did not setEngine(Engine myEngine), You must setEngine(Engine myEngine) after start program !!!");
        }

        myEngine.setDevMode(true);
        myEngine.setEncoding("UTF-8");
        //设置模板所在路径
        myEngine.setBaseTemplatePath(path);
        Template template = myEngine.getTemplate(htmlTmp);
        return template.renderToString(data);
    }
}
